import { useMessage, useDialog, useNotification, useLoadingBar } from 'naive-ui';
import {NDataTable,DataTableProps,NDrawer,NDrawerContent,NCard} from "naive-ui";
import {NButton,NDropdown, NTag, NIcon,NSpace} from "naive-ui";
import {Search} from "@vicons/ionicons5";
import {Component, ComponentProps, Hook, Link, Mut, VueComponent} from "vue3-oop";
import styles from './index.module.scss';
import SearchBar from "@/components/tool/SearchBar";
import DynaTablePanel from '@/components/panel/DynaTablePanel'
import DynaTableViewApi from './index.api'

interface IProps {
  maxWidth?: number,
  maxHeight?: number,
  info: string
}
@Component()
export default class DynaTableView extends VueComponent<IProps> {
  static defaultProps: ComponentProps<IProps> = {
    maxWidth:{default:300},
    maxHeight:{default:200},
    info:{default:''}
  }

  @Mut() info = '';
  // 主键字段
  @Mut() keyColumn = 'id';
  // 快速搜索默认值
  @Mut() searchValue = '';
  // 打开高级搜索表单
  @Mut() showSForm = false;
  // 工具栏
  @Mut() toolbar = {
    left:[] as any[],// 左边
    middle:[] as any[],// 中间
    right:[] as any[],// 右边
    visible: false
  };
  // 表格列
  @Mut() columns = [] as any[];
  // 表格数据
  @Mut() data = [] as any[];
  // 分页设置
  @Mut() page = {
    sizePicker: true,
    pageSizes: [10,20,50,100],
    pageSize: 10,
    current: 1,
    total: 0,
    jumper: true,
    onChange: (page:number) => {// 切换页
      this.page.current = page;
    },
    onReSize: (size:number) => {// 切换页大小
      this.page.pageSize = size;
      this.page.current = 1;
    },
  };
  @Mut() checked = [] as any[];

  @Link() dynaTablePanel?:DynaTablePanel;

  constructor(

  ) {
    super();
  }

  // （工具栏操作）新建
  handleCreate=()=>{
    console.log('handleCreate');
  }

  // （工具栏操作）删除
  handleRemove=()=>{
    console.log("handleRemove");
  }

  // （行操作）编辑
  handleRowEdit=(row:any)=>{
    console.log("handleRowEdit",row);
  }

  // （行操作）删除
  handleRowRemove=(row:any)=>{
    console.log("handleRowRemove",row);
  }

  // 点击数据
  handleRowClick=(row:any)=>{
    // console.log("handleRowClick",row);
  }

  // 双击数据
  handleRowDbClick=(row:any)=>{
    console.log("handleRowDbClick",row);
  }

  // 快速搜索
  quickSearch=(value:string)=>{
    console.log(value);
  }

  // 高级搜索
  sformSearch=()=>{
    console.log("sformSearch");
  }

  // 开关高级搜索表单
  toggleSForm=()=>{
    this.dynaTablePanel?.toggleSForm();
  }

  // 加载表格信息
  @Hook('Mounted')
  loadTableInfo(){
    if(this.props.info.length>0&&this.props.info!==this.info){

      DynaTableViewApi.tableInfo(this.props.info).then(({data})=>{
        console.log(data);

        const {content} = data;
        // console.log(content)
        this.columns = this.parseColumns(content.columns);

        // 多选框
        if(content.selection.enable){
          this.columns = [
            {
              key:'SYS_ROW_SELECTION',
              type:'selection',
              disabled:(row:any,index:number)=>{
                return false;
              }
            },
            ...this.columns
          ]
        }

        // 行操作
        if(content.rowAction.enable){
          this.columns.push({
            key:'SYS_ROW_ACTIONS',
            title:'操作',
            render: (row:any)=>(<NSpace size="small">{this.parseRowActions(row,content.rowAction.actions)}</NSpace>)
          })
        }

        this.toolbar.left = this.parseToolbar(content.toolbar.left);
        this.toolbar.middle = this.parseToolbar(content.toolbar.middle);
        this.toolbar.right = this.parseToolbar(content.toolbar.right);
        this.toolbar.visible = content.toolbar.visible;

        const dataInfo = content.dataInfo[0].info;
        DynaTableViewApi.tableData(dataInfo).then(({data})=>{
          const {content} = data;
          const {tableData} = content;

          this.data = tableData.records.map((item:any)=>{
            return item;
          });

        });

      })
    }
  };

  // 转为表格列配置
  parseColumns=(columns:any[]):any[]=>{
    const tableCols = [] as any[];
    for(let column of columns){
      if(column.isKey){
        this.keyColumn = column.key;
      }
      if(column.visible){
        tableCols.push(column);
      }
    }
    return tableCols;
  };

  // 转为行操作按钮
  parseRowActions=(row:any,actions:any[])=>{
    const moreOptions = [];
    const rowActions = [];

    for(let item of actions){
      if(item.inMore){
        moreOptions.push({
          key:moreOptions.length,
          label:item.title,
          type:item.type,
          props:{
            onClick:(e:MouseEvent)=>{
              e.stopPropagation();
              this.handleRowActions(item,row);
            }
          }
        });
      }else{
        const handleClick= (e:MouseEvent)=>{
          e.stopPropagation();
          this.handleRowActions(item,row);
        };
        rowActions.push(<NButton size="small" onClick={handleClick}>{item.title}</NButton>);
      }
      if(moreOptions.length>0){
        rowActions.push(<NDropdown options={moreOptions}><NButton size="small">{"更多"}</NButton></NDropdown>);
      }
    }
    return rowActions;
  }

  // 表格顶部工具栏
  parseToolbar=(actions:any[])=>{
    const moreOptions = [];
    const toolbarActions = [] as any[];

    for(let item of actions){
      if(item.type==='SYS_TITLE'){// 标题
        toolbarActions.push(
          <NTag
            bordered={false}
            size={'large'}
            style={{fontSize:'18px'}}
            color={{color:'whitesmoke'}}
          >
            {{
              avatar: ()=>(<NIcon><Search/></NIcon>),
              default: ()=>(item.title)
            }}
          </NTag>
        );
      }else if(item.type==='SYS_SEARCH'){// 快速搜索
        toolbarActions.push(
          <SearchBar
            onSearch={this.quickSearch}
            defaultValue={this.searchValue}
            showSenior={item.sformButton=='true'}
            toggleSenior={this.toggleSForm}
          />
        );
      } else{
        if(item.inMore){
          moreOptions.push({
            key:moreOptions.length,
            label:item.title,
            type:item.type,
            props:{
              onClick:(e:MouseEvent)=>{
                e.stopPropagation();
                this.handleActions(item);
              }
            }
          });
        }else{
          const handleClick= (e:MouseEvent)=>{
            e.stopPropagation();
            this.handleActions(item);
          }
          toolbarActions.push(<NButton onClick={handleClick}>{item.title}</NButton>)
        }
      }
    }
    if(moreOptions.length>0){
      toolbarActions.push(<NDropdown options={moreOptions}><NButton>{"更多"}</NButton></NDropdown>);
    }

    return toolbarActions;
  }

  handleUpdateCheckedRowKeys=(keys:Array<string|number>)=>{
    // console.log('handleUpdateCheckedRowKeys');
    this.checked = keys;
  }

  // 工具栏操作
  handleActions= (action:any)=>{
    if(action.type==='SYS_CREATE'){// 新建
      this.handleCreate();
    }else if(action.type==='SYS_REMOVE'){// 删除
      this.handleRemove();
    }else if(action.type==='SYS_SFORM'){// 高级搜索
      this.toggleSForm();
    }
  }

  // 行操作
  handleRowActions= (action:any,row:any)=>{
    if(action.type==='SYS_ROW_EDIT'){// 编辑
      this.handleRowEdit(row);
    }else if(action.type==='SYS_ROW_REMOVE'){// 删除
      this.handleRowRemove(row);
    }
  }

  render() {

    const cardPadding = 10,toolbarHeight = this.toolbar.visible?44:0;
    const tableHeight = (this.props.maxHeight as number) - 2*cardPadding - toolbarHeight;

    return (
      <DynaTablePanel
        ref="dynaTablePanel"
        maxHeight={this.props.maxHeight as number}
        maxWidth={this.props.maxWidth as number}
        // ref={stdTable}
        keyColumn={this.keyColumn}
        toolbar={this.toolbar}
        onRowClick={this.handleRowClick}
        onRowDbClick={this.handleRowDbClick}
        sformSearch={this.sformSearch}
        nDataTableProps={{
          columns: this.columns,
          onUpdateCheckedRowKeys: this.handleUpdateCheckedRowKeys,
          checkedRowKeys: this.checked,
          data: this.data,
          pagination:{
            showSizePicker: this.page.sizePicker,
            pageSizes: this.page.pageSizes,
            pageSize: this.page.pageSize,
            page: this.page.current,
            itemCount: this.page.total,
            showQuickJumper: this.page.jumper,
            onChange: this.page.onChange,
            onUpdatePageSize: this.page.onReSize,
            prefix: ()=>(
              <NSpace>
                <NTag >总共 {this.page.total} 项</NTag>
                <NTag >已选 {this.checked.length} 项</NTag>
              </NSpace>
            )
          },
        }}
      />
    )
  }
}

